#!/usr/bin/env sh

set -eu

: ${CONTINUOUS_INTEGRATION=}
: ${DOCKER_BUILDKIT=}

progressFlag=""
if [ "$CONTINUOUS_INTEGRATION" = "true" ]; then progressFlag="--progress=plain"; fi

cacheOnlyFlag=""
if ! docker build --help 2>&1 | grep buildx >/dev/null; then cacheOnlyFlag="-o type=cacheonly"; fi

case ${1:-} in
  '')
    export DOCKER_BUILDKIT=1
    docker build $progressFlag $cacheOnlyFlag -f ./hack/dockerfiles/gomod.Dockerfile --target validate . || exit 1
    ;;
  check)
    status="$(git status --porcelain -- go.mod go.sum bench/go.mod bench/go.sum 2>/dev/null)"
    diffs=$(echo "$status" | grep -v '^[RAD] ' || true)
    if [ "$diffs" ]; then
      {
        set +x
        echo 'The result of "./hack/validate-gomod" differs'
        echo
        echo "$diffs"
        echo
        echo 'Please vendor your package with "./hack/update-gomod"'
        echo
      } >&2
      exit 1
    fi
    echo 'Congratulations! go.mod is done the right way.'
    ;;
esac
